package cn.ococci.dm.Base;


import android.content.Intent;

import java.util.Stack;

import cn.ococci.dm.Main.Activity.LoginActivity;
import cn.ococci.dm.Main.CrashHandler;
import cn.ococci.dm.Main.Tools.DialogTool;
import cn.ococci.dm.Main.Tools.ThreadTool;
import cn.ococci.dm.Main.View.Dialog.DialogAdapter;
import cn.ococci_dm.R;


/**
 * Created by cyan on 15/5/24.
 * activity 栈的管理
 */
public class ActivityStack {

    private static Stack<BaseActivity> stack = new Stack<>();

    // 退出栈顶Activity
    public static void popActivity(BaseActivity activity) {
        if (activity != null) {
            // 在从自定义集合中取出当前Activity时，也进行了Activity的关闭操作
            stack.remove(activity);
            activity.finish();
        }
    }

    // 获得当前栈顶Activity
    public static BaseActivity currentActivity() {
        BaseActivity activity = null;
        if (!stack.empty())
            activity = stack.peek();
        return activity;
    }

    // 将当前Activity推入栈中
    public static void push(BaseActivity activity) {
        stack.push(activity);
    }

    // 弹出栈顶的activity并结束activity
    public static void pop() {
        stack.pop().finish();
    }

    // 清除所有activity
    public static void clear() {
        while (!stack.isEmpty())
            stack.pop().finish();

    }

    /**
     * 注销
     */
    public static void doLogout() {
        if (stack == null || stack.size() == 0) {
            return;
        }
        BaseActivity activity = stack.pop();
        clear();
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
        activity.finish();
    }



    public static void openCrash() {
        if (stack == null || stack.size() == 0) {
            return;
        }
        final BaseActivity activity = stack.peek();
        ThreadTool.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                DialogTool.createMaterialDialog(activity, new DialogAdapter() {
                    @Override
                    public void cancel() {
                        CrashHandler.getInstance().sendCrashReportsToServer(true);
                    }

                    @Override
                    public boolean confirm() {
                        CrashHandler.getInstance().sendCrashReportsToServer(false);
                        return true;
                    }

                    @Override
                    public CharSequence caption() {
                        return "异常处理";
                    }

                    @Override
                    public CharSequence getMsg() {
                        return BaseApp.findResIdDecoderString(R.string.crash_msg);
                    }
                });

            }
        });
    }


}
